//
//  AppDelegate.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2018/12/12.
//  Copyright © 2018 Gox_WallyDiao. All rights reserved.
//

import UIKit
import AVFoundation
import SwiftyStoreKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, WXApiDelegate, JPUSHRegisterDelegate {

    var window: UIWindow?
    weak var tabbarVC:TTTabBarController?
    
    static  let shareAppDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
    
    class func getAppDelegate() ->AppDelegate{
        return shareAppDelegate
    }


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 注册后台播放
        let session = AVAudioSession.sharedInstance()
        do {
            try session.setActive(true)
            if #available(iOS 10.0, *) {
                try session.setCategory(AVAudioSession.Category.playback, mode: .default, options: .allowAirPlay)
            } else {
                // Fallback on earlier versions
            }
        } catch {
            print(error)
        }
        
        // 微信登录
        WXApi.registerApp(WX_APPID)
        
        SwiftyStoreKit.completeTransactions(atomically: true) { (purchases) in
            for purchase in purchases {
                switch purchase.transaction.transactionState {
                case .purchased, .restored:
                    if purchase.needsFinishTransaction {
                        // Deliver content from server, then:
                        SwiftyStoreKit.finishTransaction(purchase.transaction)
                    }
                // Unlock content
                case .failed, .purchasing, .deferred:
                    break // do nothing
                }
            }
        }
        
        // 极光推送
        // 通知注册实体类
        if #available(iOS 10.0, *){
            let entiity = JPUSHRegisterEntity()
            entiity.types = Int(UNAuthorizationOptions.alert.rawValue |
                UNAuthorizationOptions.badge.rawValue |
                UNAuthorizationOptions.sound.rawValue)
            JPUSHService.register(forRemoteNotificationConfig: entiity, delegate: self)
        } else if #available(iOS 8.0, *) {
            let types = UIUserNotificationType.badge.rawValue |
                UIUserNotificationType.sound.rawValue |
                UIUserNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: types, categories: nil)
        }else {
            let type = UIRemoteNotificationType.badge.rawValue |
                UIRemoteNotificationType.sound.rawValue |
                UIRemoteNotificationType.alert.rawValue
            JPUSHService.register(forRemoteNotificationTypes: type, categories: nil)
        }
        // 注册极光推送
        JPUSHService.setup(withOption: launchOptions, appKey: "e65cfaa5bf43f92be2f00f1c", channel: "app store", apsForProduction: false)
        JPUSHService.registrationIDCompletionHandler { (resCode: Int32, registrationId: String?) in
            let userDefaults = UserDefaults.standard
            userDefaults.setValue(registrationId, forKey: "RegistrationID")
            print(resCode, registrationId ?? "0")
        }
        let userDefaults = UserDefaults.standard
        userDefaults.setValue(JPUSHService.registrationID(), forKey: "RegistrationID")
        
        UIApplication.shared.applicationIconBadgeNumber = 0;
        
        let userd = UserDefaults.standard
        if userd.dictionary(forKey: PlayDictionary) == nil {
            let dic = NSDictionary.init()
            userd.set(dic, forKey: PlayDictionary)
        }

        

        return true
    }
    
//  MARK: - ###### 微信部分 ######
    //  微信跳转回调
    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        
        WXApi.handleOpen(url, delegate: self)
        return true
        
    }
    
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        WXApi.handleOpen(url, delegate: self)
        return true
    }
    //  微信回调
    func onResp(_ resp: BaseResp!){
        if resp is SendAuthResp {
            if resp.errCode == 0 {
                let myResp:SendAuthResp = resp as! SendAuthResp
                print(myResp.code)
                //使用通知方法把回调返回到需要的控制器
                //            NotificationCenter.default.addObserver(self, selector: #selector(addNotic(notice:)), name: NSNotification.Name(rawValue: "MyNotice"), object: nil)
                ///发送通知
                NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "WXLoginSuccessNotification"), object: nil, userInfo: ["str":myResp.code])
            }
        } else if resp is SendMessageToWXResp {
            let send = resp as? SendMessageToWXResp
            if let sm = send {
                if sm.errCode == 0 {
                    TTAlertView.showMessage(message: "分享成功")
                    
                } else {
                    TTAlertView.showMessage(message: "分享失败")
    
                }
            }
        }
    }
    
//  MARK: - ###### 极光推送 ######
    // 打开状态收取消息，消息没有点击
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) {
        print(">JPUSHRegisterDelegate jpushNotificationCenter willPresent")
        let userInfo = notification.request.content.userInfo
        if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
        }
        completionHandler(Int(UNAuthorizationOptions.alert.rawValue))// 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
    }
    
    // 未打开，后台未关闭收到消息并点击
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) {
        print(">JPUSHRegisterDelegate jpushNotificationCenter didReceive");
        UIApplication.shared.applicationIconBadgeNumber = 0
        let userInfo = response.notification.request.content.userInfo
        print(userInfo)
        if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))!{
            JPUSHService.handleRemoteNotification(userInfo)
            //            let time: TimeInterval = 2.0
            //            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + time) {
            //                let newsVC = DDMineNewsPresentVc()
            //                newsVC.extrakey = userInfo["extrakey"] as? String ?? "跟投消息"
            //                self.window?.rootViewController?.dismiss(animated: true, completion: nil)
            //                self.window?.rootViewController?.present(newsVC, animated: true, completion: nil)
            //            }
        }
        completionHandler()
    }
    
    @available(iOS 10.0, *)
    func jpushNotificationCenter(_ center: UNUserNotificationCenter!, openSettingsFor notification: UNNotification?) {
        
    }
    
    // 注册APNs成功并上报DeviceToken
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        JPUSHService.registerDeviceToken(deviceToken)
        
    }
    
    // 程序关闭时调用
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        JPUSHService.handleRemoteNotification(userInfo)
        completionHandler(.newData)
        
    }
    
    // 程序运行时调用
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        JPUSHService.handleRemoteNotification(userInfo)
    }
    
    // 接收到推送实现的方法
    func receivePush(_ userInfo : Dictionary<String,Any>) {
        // 角标变0
        UIApplication.shared.applicationIconBadgeNumber = 0
        
    }

//  MARK: - ###### 生命周期 ######
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        TTNotificationCenter.Post(CurrentTimeStamp, obj: ["timeStamp":TIMESTMP(), "isEnterBackground":"1"])
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        TTNotificationCenter.Post(CurrentTimeStamp, obj: ["timeStamp":TIMESTMP(), "isEnterBackground":"0"])
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        TTAudioPlayer.uploadProgress()
        TTAudioPlayer.uploadDate()
    }
    
    func applicationDidReceiveMemoryWarning(_ application: UIApplication) {
        
    }


}

